from ..layouts.grid_layout import TgGridLayout
from ..layouts.vbox_layout import TgVBoxLayout
from ..inputs.label import TgLabel
from ..inputs.line_edit import TgLineEdit
from ..buttons.button import TgButton
from PySide6.QtWidgets import QWidget
from typing import List, Tuple, Dict, Any, Optional
from ..base.widget import TgBaseWidget

class TgFormLayout(TgBaseWidget):
    def __init__(self, parent: Optional[QWidget] = None, margins: str = 'medium', spacing: str = 'medium'):
        super().__init__(parent)
        
        # Main layout for the widget
        self._main_layout = TgVBoxLayout(self, margins='none', spacing='none')
        self.setLayout(self._main_layout)

        # Grid layout for the form content
        self._grid_layout = TgGridLayout(margins=margins, spacing=spacing)
        self._grid_layout.setColumnStretch(1, 1)  # Make the widget column stretchable by default
        self._main_layout.addLayout(self._grid_layout)
        
        self._main_layout.addStretch(1)
        
        self._row_index = 0

    def add_row(self, label_text: str, *widgets: QWidget, stretch: int = 0):
        """
        Adds a new row to the form layout.

        Args:
            label_text (str): The text for the row's label.
            *widgets: One or more widgets to add to the row.
            stretch (int): The stretch factor for the last widget in the row.
        """
        label = TgLabel(label_text)
        self._grid_layout.addWidget(label, self._row_index, 0)

        col_index = 1
        for widget in widgets:
            self._grid_layout.addWidget(widget, self._row_index, col_index)
            col_index += 1
        
        if stretch > 0 and widgets:
            self._grid_layout.setColumnStretch(col_index - 1, stretch)

        self._row_index += 1

    def add_row_components(self, label_text: str, components: List[Dict[str, Any]]) -> List[QWidget]:
        """
        Adds a new row to the form layout with a label and a list of components.

        Args:
            label_text (str): The text for the row's label.
            components (List[Dict[str, Any]]): A list of dictionaries, where each dictionary defines a component.
                                               Example: {"component": "button", "props": {"text": "Import"}}

        Returns:
            A list of the created widgets.
        """
        created_widgets = []
        component_map = {
            "button": TgButton,
            "line_edit": TgLineEdit,
        }

        for component_info in components:
            comp_type = component_info.get("component")
            if not isinstance(comp_type, str):
                continue
            props = component_info.get("props", {}).copy()
            
            callback = props.pop("callback", None)

            component_class = component_map.get(comp_type)
            if component_class:
                widget = component_class(**props)
                if callback and isinstance(widget, TgButton):
                    widget.clicked.connect(callback)
                created_widgets.append(widget)

        self.add_row(label_text, *created_widgets)
        return created_widgets